#include "homepage.h"
#include "ui_homepage.h"
#include <QDebug>
#define dbg qDebug()

homePage::homePage(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::homePage)
{
    ui->setupUi(this);
    dev_t.devsta = false;
    dev_t.ledsta = false;
    memset(dev_t.shidu,'\0', sizeof (dev_t.shidu));
    memset(dev_t.wendu,'\0', sizeof (dev_t.wendu));
    for (int t=0;t<10;t++) {
        client_pos[t] = true;
        devList[t]=nullptr;
    }

    server = new QTcpServer(this);
    mysocket = new QTcpSocket(this);
    server->listen(QHostAddress::Any,8888);
    connect(server,&QTcpServer::newConnection,
            [=]()
            {

                for (volatile int8_t client_num = 0;client_num<10;client_num++)
                {
                    qDebug()<<client_num;
                    if(client_pos[client_num])
                    {

                        devList[client_num] = server->nextPendingConnection();
                        QString tp = getTime();
                        devList[client_num]->write(tp.toUtf8());
                        ui->dialog->append(tp);
                        if(devList[client_num]->isWritable())
                        {
                            client_pos[client_num] = false;
                            QString ip = devList[client_num]->peerAddress().toString();
                            quint16 port = devList[client_num]->peerPort();
                            QString temp = QString("[%1:%2] 成功连接").arg(ip).arg(port);
                            ui->dialog->append(temp);
                            //ui->sendButton->setEnabled(true);
                            //处理断开连接事件
                            connect(devList[client_num],&QTcpSocket::disconnected,
                                    [=]()
                            {
                                devList[client_num] = nullptr;
                                client_pos[client_num] = true;
                                if(client_num == stm32Pos){
                                    dev_t.devsta = false;
                                    stm32Pos = -1;
                                     dev_t.ledsta = false;
                                     ui->dialog->append("offline");
                                }
                              ui->dialog->append(QString("已断开连接"));
                            }
                            );
                            //处理接收数据
                            if(devList[client_num]->isWritable())
                            connect(devList[client_num],&QTcpSocket::readyRead,
                                    [=]()
                                    {
                                        QByteArray arry = devList[client_num]->readAll();
                                        //ui->dialog->append(arry);
                                        if(strstr(arry.data(),"STM32")!=nullptr)
                                        {
                                            dev_t.devsta = true;
                                            dev_t.ledsta = false;

                                            ui->dialog->append("终端已上线");
                                            stm32Pos = client_num;
                                        }
                                        else if( strstr(arry.data(),"CLIENT")){{

                                                ui->dialog->append("客户端已上线");
                                                if(dev_t.devsta)
                                                {
                                                    if(dev_t.ledsta)
                                                        devList[client_num]->write("ON##25.00##75.00");
                                                    else
                                                        devList[client_num]->write("OFF##25.00##75.00");
                                                    qDebug()<<dev_t.devsta;
                                                }

                                            }
                                        }
                                        else {
                                            ui->dialog->append(arry);
                                            if(client_num == stm32Pos)
                                            {
                                                //dev_t.ledsta = strstr(QString(arry).section("##",0,0).toUtf8().data(),"ON") ?true:false;
                                                //dev_t.ledsta = arry.contains("ON##");
                                                if(arry.startsWith("WD")){
                                                    ui->dialog->append("请注意防盗");
                                                }
                                                else if(arry.startsWith("WF")){
                                                    ui->dialog->append("检测到火焰");
                                                }
                                                else
                                                {
                                                sprintf(dev_t.wendu,"温度:%s℃",QString(arry).section("##",1,1).toUtf8().data());
                                                sprintf(dev_t.shidu,"湿度:%s%%",QString(arry).section("##",2,2).toUtf8().data());

                                                ui->label_wendu->setText(dev_t.wendu);
                                                ui->label_shidu->setText(dev_t.shidu);
                                                 if(dev_t.ledsta)
                                                    arry.replace(1,1,"N");
                                                 else
                                                     arry.replace(1,1,"F");
                                                }



                                            }
                                            else
                                            {
                                                dev_t.ledsta = arry.contains("LEDON");
                                                //dev_t.ledsta = strstr(QString(arry).toUtf8().data(),"ON") ?true:false;

                                            }
                                            if(dev_t.ledsta)
                                            {
                                                ui->lightbt->setStyleSheet("border-image:  url(:/pic/door_on/s2.png);");
                                                ui->label_led->setText("灯：已打开");
                                            }
                                            else
                                            {
                                                ui->lightbt->setStyleSheet("border-image:  url(:/pic/door_on/s1.png);");
                                                ui->label_led->setText("灯：已关闭");
                                            }

                                            for (int8_t n = 0;n<10;n++) {
                                                if(!client_pos[n] && devList[client_num]->isOpen()){
                                                    if(n!=client_num){
                                                        {
                                                            devList[n]->write(arry.data());
                                                            qDebug()<<"已发送到->"<<n;
                                                        }
                                                    }
                                                }

                                            }
                                        }

                                    }
                                    );
                          }

                            if(!devList[client_num]->isWritable() ||!devList[client_num]->isValid())
                            {
                                devList[client_num] = nullptr;
                                client_pos[client_num] = true;
                                if(client_num == stm32Pos){
                                    dev_t.devsta = false;
                                    stm32Pos = -1;
                                     dev_t.ledsta = false;
                                     ui->dialog->append("offline");
                                }
                            }
                            break;
                    }

                }


            }
            );
}

void homePage::backup()
{
    this->show();

}
homePage::~homePage()
{
    delete ui;
}

void homePage::paintEvent(QPaintEvent *)
{
    QPixmap img;
    img.load(":/pic/bg1.jpg");
    img = img.scaled(this->width(),this->height(),Qt::IgnoreAspectRatio);
    QPainter p(this);
    p.drawPixmap(0,0,img);
}

QPixmap homePage::resizPic(QString path, int position)
{
    //设置新的图片的透明度
    QPixmap pix1_(path);

    QPixmap temp(pix1_.size());
    temp.fill(Qt::transparent);

    QPainter p1(&temp);
    p1.setCompositionMode(QPainter::CompositionMode_Source);
    p1.drawPixmap(0, 0, pix1_);
    p1.setCompositionMode(QPainter::CompositionMode_DestinationIn);

    //根据QColor中第四个参数设置透明度，此处position的取值范围是0～255
    p1.fillRect(temp.rect(), QColor(0, 0, 0, position));
    p1.end();

    pix1_ = temp;
    return pix1_;
}

void homePage::on_lightbt_clicked()
{

    if(dev_t.devsta)
    {
        QString tp = getTime();
        if(dev_t.ledsta)
        {
            dev_t.ledsta = false;
            ui->lightbt->setStyleSheet("border-image:  url(:/pic/door_on/s1.png);");
            tp.append("已关灯");
             ui->label_led->setText("灯：已关闭");
                devList[stm32Pos]->write("SEND+LEDOFF+END");

        }
        else {
            dev_t.ledsta = true;
            ui->lightbt->setStyleSheet("border-image:  url(:/pic/door_on/s2.png);");
            tp.append("已开灯");
             ui->label_led->setText("灯：已打开");
                devList[stm32Pos]->write("SEND+LEDON+END");
        }
        ui->dialog->append(tp);
    }

}

void homePage::on_beep_bt_clicked()
{
    if(dev_t.devsta)
    {
        QString tp = getTime();
        devList[stm32Pos]->write("SEND+BEEP+END");
        tp.append("已响铃");
        ui->dialog->append(tp);
    }
}

QString homePage::getTime()
{
    time_t t = time( nullptr );
    char tmp[64];
    //strftime( tmp, sizeof(tmp), "%Y/%m/%d %X: ",localtime(&t) );
    strftime( tmp, sizeof(tmp), "SEND+TIME%X+END",localtime(&t) );
    return  QString("%1").arg(tmp);
}

void homePage::on_imag_bt_clicked()
{
    if(dev_t.devsta)
    {
        QString tp = getTime();
        mysocket->write("SEND+DOOR+END");
        tp.append("已开门");
        ui->dialog->append(tp);
    }
}

